package com.car.shopping.controller;


import cn.hutool.core.bean.BeanUtil;
import com.car.commons.core.model.Result;
import com.car.commons.core.util.JwtUtil;
import com.car.commons.web.util.WebUtil;
import com.car.shopping.client.CarAccountClient;
import com.car.shopping.client.model.user.SelectAdminDto;
import com.car.shopping.client.model.user.SelectById;
import com.car.shopping.client.model.user.UserDto;
import com.car.shopping.controller.form.AddPRForm;
import com.car.shopping.entity.ProductReview;
import com.car.shopping.service.ProductReviewService;
import com.car.shopping.service.param.AddPRParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/productReview")
@Api(tags = "商品评论相关接口")
public class ProductReviewController {
    @Autowired
    private ProductReviewService productReviewService;

    @Autowired
    private CarAccountClient carAccountClient;

    @ApiOperation(value = "根据id查用户信息")
    @GetMapping("/findUserInfoById.ty")
    public Result<UserDto> findUserInfoById() throws Exception {
        String token = WebUtil.getRequest().getHeader("car-token");
        Integer userId = JwtUtil.getUserId(token);

        // 调用 Feign Client 查询用户信息
        Result<UserDto> userDtoResult = carAccountClient.findUserById(userId);

        // 检查返回结果
        if (userDtoResult.getCode() != 200) {
            return Result.getResult(UserDto.class).setMsg("获取用户信息失败").setCode(500);
        }

        // 返回用户信息
        return Result.getResult(UserDto.class).setData(userDtoResult.getData()).setMsg("查询用户信息成功").setCode(200);
    }



    @ApiOperation("根据 token 查询管理员信息")
    @GetMapping("/adminsByToken.pt")
    public Result<List<SelectAdminDto>> findsAdminByToken() throws Exception {

        String token = WebUtil.getRequest().getHeader("car-token");
        Integer adminId = JwtUtil.getAdminId(token);


        // 检查是否成功获取到管理员ID
        if (adminId == null) {
            return Result.getListResult(SelectAdminDto.class).setMsg("管理员身份验证失败").setCode(401);
        }

        // 将管理员ID放入集合
        Set<Integer> adminIds = new HashSet<>();
        adminIds.add(adminId);

        // 调用 CarAccountClient 来获取管理员信息
        Result<List<SelectAdminDto>> adminResult = carAccountClient.findsAdminByIds(adminIds);

        // 判断返回结果是否成功
        if (adminResult.getCode() != 200) {
            return Result.getListResult(SelectAdminDto.class).setMsg("获取管理员信息失败").setCode(500);
        }

        // 返回成功结果和管理员数据
        return Result.getListResult(SelectAdminDto.class).setData(adminResult.getData()).setMsg("查询管理员信息成功").setCode(200);
    }





    //根据商品id查评价
    @ApiOperation("根据商品id查评价集合")
    @GetMapping ("/selectPRById.ty")
    public Result selectPRById(Integer goodsId) throws Exception{
        List<ProductReview> result = productReviewService.selectPRById(goodsId);
        return Result.getResult().setMsg("查询商品评论成功").setData(result);
    }


    //新增用户评价（商品id，用户id，手机号，评价内容，父id(评论id)，评分）
    @ApiOperation("新增用户评价")
    @PostMapping("/addUserPR")
    public Result addUserPR(@RequestBody AddPRForm form) {
        try {
            // 1. 从请求头中获取 token
            String token = WebUtil.getRequest().getHeader("car-token");
            Integer userId = JwtUtil.getUserId(token);

            // 如果用户身份验证失败，返回 401 错误
            if (userId == null) {
                return Result.getResult().setMsg("用户身份验证失败").setCode(401);
            }

            // 2. 将表单数据转换为服务层需要的参数对象
            AddPRParam param = BeanUtil.toBean(form, AddPRParam.class);

            // 3. 调用服务层逻辑，新增用户评价
            productReviewService.addUserPR(param, userId);

            // 4. 返回成功结果
            return Result.getResult().setMsg("评论成功").setCode(200);
        } catch (Exception e) {
            // 5. 捕获异常并返回错误信息
            return Result.getResult().setMsg("评论失败：" + e.getMessage()).setCode(500);
        }
    }



    //新增平台评价（商品id，管理员id，手机号，评价内容，父id）
    @ApiOperation("新增平台回复")
    @PostMapping("/addAdminPR.pt")
    public Result addAdminPR(@RequestBody AddPRForm form) throws Exception {
        // 1. 从请求头中获取 token
        String token = WebUtil.getRequest().getHeader("car-token");

        // 2. 从 token 中解析出 adminId
        Integer adminId = JwtUtil.getAdminId(token);

        System.out.println(form);
        System.out.println(adminId);

        // 3. 调用服务层逻辑，新增平台回复
        productReviewService.addAdminPR(BeanUtil.toBean(form, AddPRParam.class), adminId);

        // 4. 返回成功结果
        return Result.getResult().setMsg("管理员评论成功").setCode(200);
    }

    //删除评价（评价id）
    @ApiOperation("删除评价")
    @PostMapping("/deleteReview.pt")
    public Result deleteReview(@RequestParam Integer reviewId) throws Exception {
        productReviewService.deleteReviewById(reviewId);
        return Result.getResult().setMsg("评论已删除").setCode(200);
    }
    @ApiOperation("查询全部评论")
    @GetMapping("/allReview.ty")
    public Result allReview() throws Exception {
        List<ProductReview> list = productReviewService.allReview();
        return Result.getResult().setMsg("查询全部评论成功").setCode(200).setData(list);
    }



}

